<?php
namespace Admin\Model;
use Think\Model;

class CategoryModel extends  Model{

    //实例化表
    protected $tableName='Category';
    protected $_validate=array(
        array('sort','require','排序不能为空'),
        array('cname','require','类名不能为空 '),
        array('cname','','类名已经存在',0,'unique',1),

    );

    /*
     * 返回树状形式的数据
     * */
    public function getTree()
    {
        $data=$this->select();
        return $this->reSort(($data));
    }

     /*
     * 重建数组
      * $data所有分类数组
      * $parentid父级的id
      * 分类的id
      *  */
    protected function reSort($data,$parentid=0,$level=0)

    {
        //p($data);
        static $result = [];
        foreach ($data as $k=>$v)
        {
          if ($v['pid']==$parentid)
          {
              $v['level']=$level;
              $result[] = $v;
              $this->reSort($data,$v['id'],$level+1);
          }
        }
        return $result;
    }

    public function getNoMy($id){

         $ids=$this->getSon($this->select(),$id);
         //p($ids);die();
        $ids[]= $id;
        $data=$this->where("id NOT IN(".implode(',',$ids).")")->select();
        //p($data);die();
        //p($this->reSort($data));die();
        return $this->reSort($data);

    }

    private function getSon($data,$id){
        $temp = [];

        foreach ($data as $k=>$v){
            //如果当前循环中的pid等于我们要编辑的记录的id
            if($v['pid']==$id){
                //把当前的记录的 id传入给临时数组
                $temp[]=$v['id'];
                //递归执行，并合并$temp
                $temp=array_merge($temp,$this->getSon($data,$v['id']));
            }
        }
        return $temp;
    }
}